<?php
namespace app\service;
use think\Db;
use think\Config;

class UsageLimitService
{

    protected $_daily_limits;

    public function __construct()
    {
        $this->_daily_limits = Config::get('daily_limits');
    }

    public function getDailyLimits()
    {
        $user_type = 'guest';

        $userService = new UserService();
        $userInfo = $userService->getUserInfo();
        if ($userInfo) {
            $user_type = isset($userInfo['user_type']) ? $userInfo['user_type'] : 'user';
        }
        return $this->_daily_limits[$user_type];
    }

    public function getRemainingCount()
    {
        
        $used_count = $this->getUsedCount();
        $user_limit = $this->getDailyLimits();
        $remaining_count = $user_limit - $used_count;
        if ($remaining_count < 0) $remaining_count = 0;
        return $remaining_count;
    }
    public function getUsedCount()
    {
        $today = date('Y-m-d');
        $userService = new UserService();
        $userInfo = $userService->getUserInfo();
        $user_id = $userService->getUserId();
        $user_type = isset($userInfo['user_type']) ? $userInfo['user_type'] : 'guest';
        if ($user_type == 'guest') {
            $ip_address = get_client_ip();
            $user_count = Db::table('operations')
                ->where(function($query) use ($ip_address, $user_id) {
                    $query->where('ip_address', $ip_address)
                        ->whereOr('user_id', $user_id);
                })
                ->where('status', 'completed')
                ->where('created_at', 'like', $today . '%')
                ->count();

        } else {
            $user_count = Db::table('operations')
                ->where('user_id', $user_id)
                ->where('status', 'completed')
                ->where('created_at', 'like', $today . '%')
                ->count();
        }
        return $user_count;
    }
    /**
     * Check daily limits
     */
    function checkDailyLimit()
    {
        $today = date('Y-m-d');
        
        
        $userService = new UserService();
        $userInfo = $userService->getUserInfo();
        $user_id = $userService->getUserId();
        $user_type = isset($userInfo['user_type']) ? $userInfo['user_type'] : 'guest';

        if ($user_type == 'guest') {
            $ip_address = get_client_ip();
            // 游客用户 根据ip地址判断
            $user_count = Db::table('operations')
                ->where('ip_address', $ip_address)
                ->whereOr('user_id',$user_id)
                ->where('status', 'completed')
                ->where('created_at', 'like', $today . '%')
                ->count();

        }else if ($user_type == 'user') {
            // 获取用户操作次数
            $user_count = Db::table('operations')
            ->where('user_id', $user_id)
            ->where('status', 'in', ['completed','pending','processing'])
            ->where('created_at', 'like', $today . '%')
            ->count();
        }


        $limit = $this->_daily_limits[$user_type];
        if ($user_type == 'guest') {
            $user_type_name = '遊客';
            $limit_message = "{$user_type_name}每日產生限制（{$limit}次/天）请绑定Google帳號后享受更多產生次數";
        } else {
            $user_type_name = '用戶';
            $limit_message = "{$user_type_name}每日產生限制（{$limit}次/天）.已達到，請明天繼續。";
        }
        if ($user_count >= $limit) {
            return ['status' => false, 'message' => $limit_message,'user_type' => $user_type];
        }
        
        return ['status' => true, 'message' => '每日產生限制檢查通過。','user_type' => $user_type];
    }

    /**
     * Record operation
     */
    function recordOperation($status = 'pending')
    {
        
        $ip_address = get_client_ip();
        $userService = new UserService();
        $user_id = $userService->getUserId();
        $data = [
            'ip_address' => $ip_address,
            'user_id' => $user_id,
            'status' => $status,
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        return Db::table('operations')->insertGetId($data);
    }
    public function updateOperation($operation_id,$status)
    {
        $data = [
            'status' => $status,
            'updated_at' => date('Y-m-d H:i:s')
        ];
        return Db::table('operations')->where('id', $operation_id)->update($data);
    }
    
}
